package org.helyx.gae.getabike.provider.normalizer;

import org.helyx.gae.getabike.model.Station;

public class VelibStationInfoNormalizer implements StationInfoNormalizer {

	protected static final char DEFAULT_SPLITTER = '-';
	protected static final String TPE_PATTERN = "(CB)";
	protected char splitter = DEFAULT_SPLITTER;

	public VelibStationInfoNormalizer() {
		this(DEFAULT_SPLITTER);
	}

	public VelibStationInfoNormalizer(char splitter) {
		super();
		this.splitter = splitter;
	}


	public void normalizeName(Station station) {
		
		if (station == null) {
			return ;
		}
		
		String nameToNormalize = station.getName();
	
		int firstSplitterIndex = nameToNormalize.indexOf(splitter);
		if (firstSplitterIndex >= 0) {
			int stationIdIndex = nameToNormalize.indexOf(String.valueOf(station.getNumber()));
			
			if (stationIdIndex >= 0 && stationIdIndex < firstSplitterIndex) {
				station.setName(nameToNormalize.substring(firstSplitterIndex + 1).trim());
			}
		}
		
		int stationAddressLength = station.getAddress().length();
		int stationFullAddressLength = station.getFullAddress().length();
		
		if (station.getFullAddress().startsWith(station.getAddress()) && stationFullAddressLength - stationAddressLength > 5) {
			int index = stationAddressLength;
			if (index >= 0) {
				station.setZipCode(station.getFullAddress().substring(index + 1, index + 1 + 5));
				station.setCity(station.getFullAddress().substring(index + 1 + 5 + 1));
			}
		}

		
		int separatorIndex = station.getAddress().lastIndexOf(splitter);
		if (separatorIndex > 0) {
			station.setAddress(station.getAddress().substring(0, separatorIndex).trim());
		}
		
		station.setFullAddress(station.getAddress());
		
		int tpeIndex = station.getName().indexOf(TPE_PATTERN);
		if (tpeIndex >= 0) {
			station.setTpe(true);
			station.setName(station.getName().substring(0, tpeIndex).trim());
		}

	}

}
